package com.yuantong.xyerp.rest.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.yuantong.xyerp.core.api.form.QueryForm;
import com.yuantong.xyerp.core.api.model.CashFlow;
import com.yuantong.xyerp.core.api.service.ICashFlowService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

/**
 * Created by Jianguo.Yin on 2021-07-15.
 */
@Slf4j
@Api(tags = "账户接口")
@RestController
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private ICashFlowService cashFlowService;


    @ApiOperation(value = "导出流水", notes = "选择导出的id,只用给id赋值", produces = "application/octet-stream")
    @PostMapping(value = "/export",produces = "application/octet-stream;charset=utf-8")
    public void exportCashFlow(HttpServletResponse response,
                               @ApiParam("查询参数") @RequestBody QueryForm queryForm) {
        // List<CashFlow> cashFlowList = cashFlowService.findByFuzz(null,null,null,null);
        List<CashFlow> cashFlowList = cashFlowService.findByFuzz(queryForm.getStartTime(), queryForm.getEndTime(), queryForm.getFuzzy(), queryForm.getIds());
        ExportParams params = new ExportParams("明细表", "明细表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(params, CashFlow.class, cashFlowList);
        ServletOutputStream outputStream = null;
        try {
            response.setContentType("application/octet-stream");
            //中文乱码
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("明细表.xls", "UTF-8"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != outputStream) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
